package com.hzmall.service.impl;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.alipay.demo.trade.config.Configs;
import com.alipay.demo.trade.model.ExtendParams;
import com.alipay.demo.trade.model.GoodsDetail;
import com.alipay.demo.trade.model.builder.AlipayTradePrecreateRequestBuilder;
import com.alipay.demo.trade.model.result.AlipayF2FPrecreateResult;
import com.alipay.demo.trade.service.AlipayTradeService;
import com.alipay.demo.trade.service.impl.AlipayTradeServiceImpl;
import com.alipay.demo.trade.utils.ZxingUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hzmall.common.Const;
import com.hzmall.common.ServerResponse;
import com.hzmall.dao.*;
import com.hzmall.pojo.*;
import com.hzmall.service.IOrderService;
import com.hzmall.util.*;
import com.hzmall.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.math.BigDecimal;
import java.util.*;

@Service("orderService")
@Slf4j
public class OrderService implements IOrderService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private CartMapper cartMapper;
    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private OrderItemMapper orderItemMapper;
    @Autowired
    private ShippingService shippingService;
    @Autowired
    private ShippingMapper shippingMapper;
    @Autowired
    private PayInfoMapper payInfoMapper;

    private String filePath;

    private static AlipayTradeService tradeService;
    static {
        Configs.init("zfbinfo.properties");
        tradeService = new AlipayTradeServiceImpl.ClientBuilder().build();
    }
    /**
     * 生成订单
     */
    public ServerResponse create(Integer userId, Integer shippingId){
        OrderVo orderVo = new OrderVo();
        orderVo.setOrderNo(makeOrderNo()); //设置订单编号
        List<OrderItemVo> orderItemVoList = getProductFromCart(userId);
        orderVo.setOrderItemVoList(orderItemVoList);
        BigDecimal payment = new BigDecimal("0");  //设置订单总价
        for (OrderItemVo orderItemVo : orderItemVoList){
            payment = BigDecimalUtil.add(payment.doubleValue(),orderItemVo.getTotalPrice().doubleValue());
        }
        orderVo.setPayment(payment);  //订单总价
        orderVo.setPaymentType(Const.PAY_INFO.ONLINE_PAY.getCode());  //默认支付方式，在线付款-支付宝
        orderVo.setPostage(Long.parseLong("0"));  //物流单号,默认0
        orderVo.setShippingId(shippingId);  //设置收货地址信息
        orderVo.setShippingVo(shippingService.convertShipping2ShippingVo(this.shippingMapper.selectByPrimaryKey(shippingId)));
        orderVo.setStatus(Const.ORDER_STATUS.NO_PAY.getCode());//0-已取消-10-未付款，20-已付款，40-已发货，50-交易成功，60-交易关闭
        orderVo.setCreateTime(new Date());
        Integer rows = this.orderMapper.insert(convertOrderVo2Order(orderVo,userId));  //生成订单
        if (rows > 0){  //生成订单成功后进行的操作
            for (OrderItemVo orderItemVo : orderItemVoList){
                orderItemVo.setOrderNo(orderVo.getOrderNo());
                orderItemVo.setCreateTime(orderVo.getCreateTime());
                this.orderItemMapper.insert(convertOrderItemVo2OrderItem(orderItemVo,userId)); //1.更新OrderItem数据库表
                this.productMapper.reduceProductStock(orderItemVo.getProductId(),orderItemVo.getQuantity()); //2.对应商品减库存
            }
            RedisShardedPoolUtil.set(String.valueOf(userId), JsonUtil.obj2String(orderVo));//记录当前订单数据到Redis
            cleanCart(userId);
            return ServerResponse.createBySuccess(orderVo,"创建订单成功");
        }
      return ServerResponse.createByErrorMessage("订单创建失败");
    }

    //Cart对象转OrderItemVo对象
    private OrderItemVo convertCart2OrderItemVo(Cart cart){
        Product product = this.productMapper.selectByPrimaryKey(cart.getProductId());
        OrderItemVo orderItemVo = new OrderItemVo();
        orderItemVo.setCurrentUnitPrice(product.getPrice());
        orderItemVo.setImageHost(PropertiesUtil.getStringProperty("ftp.server.http.prefix"));
        orderItemVo.setProductId(cart.getProductId());
        orderItemVo.setProductImage(product.getMainImage());
        orderItemVo.setProductName(product.getName());
        orderItemVo.setQuantity(cart.getQuantity());
        orderItemVo.setTotalPrice(BigDecimalUtil.mul(cart.getQuantity().doubleValue(),product.getPrice().doubleValue()));
        return orderItemVo;
    }
    //OrderItemVo对象转OrderItem对象
    private OrderItem convertOrderItemVo2OrderItem(OrderItemVo orderItemVo, Integer userId){
        OrderItem orderItem = new OrderItem();
        orderItem.setOrderNo(orderItemVo.getOrderNo());
        orderItem.setCreateTime(orderItemVo.getCreateTime());
        orderItem.setCurrentUnitPrice(orderItemVo.getCurrentUnitPrice());
        orderItem.setProductId(orderItemVo.getProductId());
        orderItem.setProductImage(orderItemVo.getProductImage());
        orderItem.setProductName(orderItemVo.getProductName());
        orderItem.setQuantity(orderItemVo.getQuantity());
        orderItem.setTotalPrice(orderItemVo.getTotalPrice());
        orderItem.setUserId(userId);
        return orderItem;
    }

    //OrderVo对象转Order对象
    private Order convertOrderVo2Order(OrderVo orderVo, Integer userId){
        Order order = new Order();
        order.setOrderNo(orderVo.getOrderNo());
        order.setPayment(orderVo.getPayment());
        order.setPaymentType(orderVo.getPaymentType());
        order.setPostage(Integer.parseInt(String.valueOf(orderVo.getPostage())));
        order.setShippingId(orderVo.getShippingId());
        order.setStatus(orderVo.getStatus());
        order.setUserId(userId);
        return order;
    }
    //生成订单号码
    private Long makeOrderNo(){
        return System.currentTimeMillis()+System.currentTimeMillis() % 9;
    }

    //获取订单的商品信息
    public ServerResponse getOrderCartProduct(Integer userId){
        String orderVoStr = RedisShardedPoolUtil.get(String.valueOf(userId));
        OrderVo orderVo = JsonUtil.string2Obj(orderVoStr,OrderVo.class);
        assert orderVo != null;
        List<OrderItemVo> orderItemVoList = orderVo.getOrderItemVoList();
        OrderCartProductVo orderCartProductVo = new OrderCartProductVo();
        orderCartProductVo.setImageHost(PropertiesUtil.getStringProperty("ftp.server.http.prefix"));
        orderCartProductVo.setOrderItemVoList(orderItemVoList);
        BigDecimal productTotalPrice = new BigDecimal("0");
        for (OrderItemVo orderItemVo : orderItemVoList){
            productTotalPrice = BigDecimalUtil.add(productTotalPrice.doubleValue(),orderItemVo.getTotalPrice().doubleValue());
        }
        orderCartProductVo.setProductTotalPrice(productTotalPrice);
        return ServerResponse.createBySuccess(orderCartProductVo);
    }

    //从购物车获取商品，并转换成OrderItemVo对象
    private List<OrderItemVo> getProductFromCart(Integer userId){
        List<Cart> cartList = this.cartMapper.selectCartByUserIdChecked(userId); //从购物车中获取勾选的商品
        List<OrderItemVo> orderItemVoList = new ArrayList<OrderItemVo>();
        for (Cart cartItem : cartList){//生成orderItemVoList
            Product product = this.productMapper.selectByPrimaryKey(cartItem.getProductId());
            if (product.getStatus() == 1 && product.getStock() > cartItem.getQuantity()) {
                OrderItemVo orderItemVo = convertCart2OrderItemVo(cartItem);
                orderItemVoList.add(orderItemVo);
            }
        }
        return orderItemVoList;
    }
    private void cleanCart(Integer userId) {
        List<Cart> cartList = this.cartMapper.selectCartByUserIdChecked(userId);
        for (Cart cart : cartList) { //订单创建成功后清除购物车选中商品
            this.cartMapper.deleteByPrimaryKey(cart.getId());
        }
    }

    //订单列表
    @Override
    public ServerResponse list(Integer userId,Integer pageNum,Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        PageHelper.orderBy("create_time"+" "+"desc");
        List<Order> orderList = this.orderMapper.selectOrdersByUserId(userId);
        List<OrderListVo> orderListVoList = new ArrayList<OrderListVo>();
        for (Order order : orderList){
            orderListVoList.add(convertOrderVo2OrderListVo(order,userId));
        }
        PageInfo pageInfo = new PageInfo(orderList);
        pageInfo.setList(orderListVoList);
        return ServerResponse.createBySuccess(pageInfo);
    }

    //orderItem转OrderItemVo
    private OrderItemVo convertOrderItem2OrderItemVo(OrderItem orderItem){
        OrderItemVo orderItemVo = new OrderItemVo();
        orderItemVo.setCreateTime(orderItem.getCreateTime());
        orderItemVo.setOrderNo(orderItem.getOrderNo());
        orderItemVo.setImageHost(PropertiesUtil.getStringProperty("ftp.server.http.prefix"));
        orderItemVo.setTotalPrice(orderItem.getTotalPrice());
        orderItemVo.setQuantity(orderItem.getQuantity());
        orderItemVo.setProductName(orderItem.getProductName());
        orderItemVo.setProductImage(orderItem.getProductImage());
        orderItemVo.setProductId(orderItem.getProductId());
        orderItemVo.setCurrentUnitPrice(orderItem.getCurrentUnitPrice());
        return orderItemVo;
    }

    //Order转OrderListVo
    private OrderListVo convertOrderVo2OrderListVo(Order order,Integer userId){
        List<OrderItem> orderItemList = this.orderItemMapper.selectOrderItemByOrderNo(userId,order.getOrderNo());
        List<OrderItemVo> orderItemVoList = new ArrayList<OrderItemVo>();
        for (OrderItem orderItem : orderItemList){
            orderItemVoList.add(convertOrderItem2OrderItemVo(orderItem));
        }
        Shipping shipping = this.shippingMapper.selectByPrimaryKey(order.getShippingId());
        ShippingVo shippingVo = this.shippingService.convertShipping2ShippingVo(shipping);
        OrderListVo orderListVo = new OrderListVo();
        orderListVo.setOrderNo(order.getOrderNo());
        orderListVo.setPayment(order.getPayment());
        orderListVo.setPaymentType(order.getPaymentType());
        orderListVo.setPaymentTypeDesc(Const.PAY_INFO.codeOf(order.getPaymentType()).getDesc());
        orderListVo.setPostage(Long.parseLong(String.valueOf(order.getPostage())));
        orderListVo.setStatus(order.getStatus());
        orderListVo.setStatusDesc(Const.ORDER_STATUS.codeOf(order.getStatus()).getDesc());
        orderListVo.setPaymentTime(DateTimeUtil.date2String(order.getPaymentTime()));
        orderListVo.setSendTime(DateTimeUtil.date2String(order.getSendTime()));
        orderListVo.setEndTime(DateTimeUtil.date2String(order.getSendTime()));
        orderListVo.setCloseTime(DateTimeUtil.date2String(order.getCloseTime()));
        orderListVo.setCreateTime(DateTimeUtil.date2String(order.getCreateTime()));
        orderListVo.setOrderItemVoList(orderItemVoList);
        orderListVo.setImageHost(PropertiesUtil.getStringProperty("ftp.server.http.prefix"));
        orderListVo.setShippingId(order.getShippingId());
        orderListVo.setShippingVo(shippingVo);
        orderListVo.setReceiverName(shippingVo.getReceiverName());
        return orderListVo;
    }

    /**
     * 订单详情
     */
    public ServerResponse detail(Integer userId, Long orderNo){
        Order order = this.orderMapper.selectOrderByUserIdAndOrderNo(userId, orderNo);
        if (order == null){
            return ServerResponse.createByErrorMessage("没有权限");
        }
        OrderListVo orderListVo = convertOrderVo2OrderListVo(order,userId);
        return ServerResponse.createBySuccess(orderListVo);
    }

    /**
     * 取消订单
     */
    public ServerResponse cancel(Integer userId,Long orderNo){
        Order order = this.orderMapper.selectOrderByUserIdAndOrderNo(userId, orderNo);
        if (order == null){
            return ServerResponse.createByErrorMessage("该用户没有此订单");
        }
        if (order.getStatus() > Const.ORDER_STATUS.NO_PAY.getCode()){
            return ServerResponse.createByErrorMessage("该订单已付款，暂不支持取消");
        }
        //开始取消订单
        Order updateOrder = new Order();
        updateOrder.setId(order.getId());
        updateOrder.setStatus(Const.ORDER_STATUS.CANCEL.getCode());
        updateOrder.setCloseTime(new Date());
        Integer rows = this.orderMapper.updateByPrimaryKeySelective(updateOrder);
        //还原商品库存
        List<OrderItem> orderItemList = this.orderItemMapper.selectOrderItemByOrderNo(userId, order.getOrderNo());
        for (OrderItem orderItem : orderItemList){
            Product product = this.productMapper.selectByPrimaryKey(orderItem.getProductId());
            if (product.getStatus() == 1){ //确认商品属于正在销售状态
                Product updateProduct = new Product();
                updateProduct.setId(product.getId());
                updateProduct.setStock(product.getStock()+orderItem.getQuantity());
                this.productMapper.updateByPrimaryKeySelective(updateProduct);
            }
        }
        if (rows > 0){
            return ServerResponse.createBySuccess();
        }
        return ServerResponse.createByErrorMessage("订单取消失败");
    }

    /**
     * 支付
     */
    public ServerResponse pay(Integer userId,Long orderNo){
        Order order = this.orderMapper.selectOrderByUserIdAndOrderNo(userId, orderNo);
        if (order == null){
            return ServerResponse.createByErrorMessage("该用户不存在该订单");
        }
        if (order.getStatus() != Const.ORDER_STATUS.NO_PAY.getCode()){
            return ServerResponse.createByErrorMessage("当前订单不是未付款状态，无法进行付款操作");
        }
        Map<String, String> resultMap = new HashMap();
        resultMap.put("orderNo",String.valueOf(order.getOrderNo()));
        String outTradeNo = String.valueOf(order.getOrderNo());
        String subject = "HzMall商城订单——在线支付";
        String totalAmount = String.valueOf(order.getPayment().doubleValue());
        String undiscountableAmount = "0";
        String sellerId = "";
        String body = "总计"+String.valueOf(order.getPayment())+"元";
        String operatorId = String.valueOf(order.getUserId());
        String storeId = "test_store_id";
        ExtendParams extendParams = new ExtendParams();
        extendParams.setSysServiceProviderId("2088100200300400500");
        String timeoutExpress = "120m";
        List<GoodsDetail> goodsDetailList = new ArrayList<GoodsDetail>();
        List<OrderItem> orderItemList = this.orderItemMapper.selectOrderItemByOrderNo(userId, order.getOrderNo());
        for (OrderItem orderItem : orderItemList){
            GoodsDetail goods1 = GoodsDetail.newInstance(String.valueOf(orderItem.getProductId()), orderItem.getProductName(), orderItem.getCurrentUnitPrice().longValue(), orderItem.getQuantity());
            goodsDetailList.add(goods1);
        }
        AlipayTradePrecreateRequestBuilder builder = new AlipayTradePrecreateRequestBuilder()
                .setSubject(subject).setTotalAmount(totalAmount).setOutTradeNo(outTradeNo)
                .setUndiscountableAmount(undiscountableAmount).setSellerId(sellerId).setBody(body)
                .setOperatorId(operatorId).setStoreId(storeId).setExtendParams(extendParams)
                .setTimeoutExpress(timeoutExpress)
                .setNotifyUrl("http://ccdemo.s1.natapp.cc/order/alipay_callback.do")//支付宝服务器主动通知商户服务器里指定的页面http路径,根据需要设置
                .setGoodsDetailList(goodsDetailList);

        AlipayF2FPrecreateResult result = tradeService.tradePrecreate(builder);
        switch (result.getTradeStatus()) {
            case SUCCESS:
                log.info("支付宝预下单成功: )");
                AlipayTradePrecreateResponse response = result.getResponse();
                dumpResponse(response);
                filePath = String.format("qr-%s.png", response.getOutTradeNo());
                String uploadName = "d:/"+filePath;
                log.info("filePath:" + filePath);
                ZxingUtils.getQRCodeImge(response.getQrCode(), 256, uploadName);
                File targetFile = new File(uploadName);
                List<File> fileList = new ArrayList<File>();
                fileList.add(targetFile);
                try {
                    if (FtpUtil.uploadFile(fileList)){
                        targetFile.delete();
                    }
                }catch (Exception e){
                    log.error("上传ftp发生异常");
                }
                resultMap.put("qrPath",PropertiesUtil.getStringProperty("ftp.server.http.prefix")+filePath);
                return ServerResponse.createBySuccess(resultMap);
            case FAILED:
                log.error("支付宝预下单失败!!!");
                return ServerResponse.createByErrorMessage("支付宝预下单失败!!!");

            case UNKNOWN:
                log.error("系统异常，预下单状态未知!!!");
                return ServerResponse.createByErrorMessage("系统异常，预下单状态未知!!!");

            default:
                log.error("不支持的交易状态，交易返回异常!!!");
                return ServerResponse.createByErrorMessage("不支持的交易状态，交易返回异常!!!");
        }
    }
    private void dumpResponse(AlipayTradePrecreateResponse response){
        if (response != null){
            log.info(response.getBody());
        }
    }

    /**
     * 处理支付宝回调
     */
    public Object alipayCallBack(Map<String,String[]> requestParams){
        Iterator iterator = requestParams.keySet().iterator();
        Map<String, String> params = new HashMap<String, String>();
        String valueStr = StringUtils.EMPTY;
        while (iterator.hasNext()){
            String name = (String) iterator.next();
            String[] values = requestParams.get(name);
            if (ArrayUtils.isNotEmpty(values)){
                if (values.length > 1){
                    for (String value : values) {
                        valueStr = valueStr + value+",";
                    }
                }else{
                    valueStr = values[0];
                }
            }
            params.put(name,valueStr);
        }
        //params.remove("sign");
        params.remove("sign_type");
        try {
            Boolean alipayCheck = AlipaySignature.rsaCheckV2(params,Configs.getAlipayPublicKey(),"utf-8",Configs.getSignType());
            if (!alipayCheck){
               return ServerResponse.createByErrorMessage("非法请求");
            }
        } catch (AlipayApiException e) {
            log.error("支付宝验签异常",e);
        }
        ServerResponse serverResponse = (ServerResponse) finalCheck(params);
        if (serverResponse.isSuccess()){
            return "success";
        }
        return "error";
    }

    //支付宝验签完成后进行本地参数校验
    private Object finalCheck(Map<String,String> param){
        String orderNo = param.get("out_trade_no");
        Order order = this.orderMapper.selectOrderByOrderNo(Long.parseLong(orderNo));
        if (order == null){
            return ServerResponse.createByErrorMessage("非本地订单");
        }
        if (Double.parseDouble(param.get("buyer_pay_amount")) != order.getPayment().doubleValue()){
            return ServerResponse.createByErrorMessage("请求异常，订单金额与实收金额不符");
        }
        if (order.getStatus() > Const.ORDER_STATUS.PAID.getCode()){
            return ServerResponse.createBySuccessMessage("支付宝重复调用");
        }
        String tradeStatus = param.get("trade_status");
        if (StringUtils.equals(Const.ALIPAY_ORDER_STATUS.TRADE_SUCCESS,tradeStatus)){
            Order updateOrder = new Order();
            updateOrder.setId(order.getId());
            updateOrder.setStatus(Const.ORDER_STATUS.PAID.getCode());
            updateOrder.setPaymentTime(DateTimeUtil.str2DateTime(param.get("gmt_payment")));
            this.orderMapper.updateByPrimaryKeySelective(updateOrder);
        }
        PayInfo payInfo = new PayInfo();
        payInfo.setOrderNo(order.getOrderNo());
        payInfo.setPayPlatform(Const.PAY_PLATFORM.ALIPAY.getCode());
        payInfo.setPlatformNumber(param.get("trade_no"));
        payInfo.setUserId(order.getUserId());
        payInfo.setPlatformStatus(tradeStatus);
        this.payInfoMapper.insert(payInfo);
        return ServerResponse.createBySuccess();
    }

    /**
     * 查询订单支付状态
     */
    public ServerResponse queryOrderPayStatus(Integer userId,Long orderNo){
        Order order = this.orderMapper.selectOrderByUserIdAndOrderNo(userId, orderNo);
        if (order == null){
            return ServerResponse.createByErrorMessage("该用户没有该订单");
        }
        if (order.getStatus() >= Const.ORDER_STATUS.PAID.getCode()){
            return ServerResponse.createBySuccess();
        }
        return ServerResponse.createByError();
    }


    /**
     * -------------------------后台----------------------------
     */


    //订单list
    public ServerResponse backendList(Integer pageSize,Integer pageNum){
        PageHelper.startPage(pageNum,pageSize);
        List<Order> orderList = this.orderMapper.selectAllOrders();
        List<OrderListVo> orderListVoList = new ArrayList<OrderListVo>();
        for (Order order : orderList){
            orderListVoList.add(convertOrder2OrderListVo(order));
        }
        PageInfo pageInfo = new PageInfo(orderList);
        pageInfo.setList(orderListVoList);
        return ServerResponse.createBySuccess(pageInfo);

    }

    //Order转OrderVo

    private OrderListVo convertOrder2OrderListVo(Order order){
        OrderListVo orderVo = new OrderListVo();
        orderVo.setCreateTime(DateTimeUtil.date2String(order.getCreateTime()));
        orderVo.setStatus(order.getStatus());
        orderVo.setShippingVo(this.shippingService.convertShipping2ShippingVo(this.shippingMapper.selectByPrimaryKey(order.getShippingId())));
        orderVo.setShippingId(order.getShippingId());
        orderVo.setPostage(Long.parseLong(String.valueOf(order.getPostage())));
        orderVo.setPaymentType(order.getPaymentType());
        orderVo.setPaymentTypeDesc(Const.PAY_INFO.codeOf(order.getPaymentType()).getDesc());
        orderVo.setOrderNo(order.getOrderNo());
        orderVo.setCloseTime(DateTimeUtil.date2String(order.getCloseTime()));
        orderVo.setEndTime(DateTimeUtil.date2String(order.getEndTime()));
        orderVo.setPaymentTime(DateTimeUtil.date2String(order.getPaymentTime()));
        orderVo.setSendTime(DateTimeUtil.date2String(order.getSendTime()));
        orderVo.setPayment(order.getPayment());
        orderVo.setReceiverName(this.shippingMapper.selectByPrimaryKey(order.getShippingId()).getReceiverName());
        orderVo.setImageHost(PropertiesUtil.getStringProperty("ftp.server.http.prefix"));

        List<OrderItem> orderItemList = this.orderItemMapper.selectOrderItemsByOrderNo(order.getOrderNo());
        List<OrderItemVo> orderItemVoList = new ArrayList<OrderItemVo>();
        for (OrderItem orderItem : orderItemList){
            orderItemVoList.add(convertOrderItem2OrderItemVo(orderItem));
        }
        orderVo.setOrderItemVoList(orderItemVoList);
        return orderVo;
    }

    //按订单号搜索
    public ServerResponse backendSearch(Long orderNo){
        Order order = this.orderMapper.selectOrderByOrderNo(orderNo);
        if (order == null){
            return ServerResponse.createByErrorMessage("订单不存在");
        }
        OrderListVo orderListVo = convertOrder2OrderListVo(order);
        return ServerResponse.createBySuccess(orderListVo);
    }

    //订单发货
    public ServerResponse sendGood(Long orderNo){
        Order order = this.orderMapper.selectOrderByOrderNo(orderNo);
        if (order == null){
            return ServerResponse.createByErrorMessage("订单不存在");
        }
        if (order.getStatus() >= Const.ORDER_STATUS.SENDED.getCode()){
            return ServerResponse.createByErrorMessage("订单状态异常,订单已发货或已完成");
        }
        if (order.getStatus() == Const.ORDER_STATUS.NO_PAY.getCode()){
            return ServerResponse.createByErrorMessage("订单未付款，不能发货");
        }
        order.setStatus(Const.ORDER_STATUS.SENDED.getCode());
        order.setSendTime(new Date());
        Integer rows = this.orderMapper.updateByPrimaryKeySelective(order);
        if (rows > 0){
            return ServerResponse.createBySuccessMessage("发货成功");
        }
        return ServerResponse.createByErrorMessage("发货失败");
    }

    /**
     * 预留：订单确认收货
     */
    public ServerResponse confirmOrder(Long orderNo){
        Order order = this.orderMapper.selectOrderByOrderNo(orderNo);
        if (order == null){
            return ServerResponse.createByErrorMessage("订单不存在");
        }
        if (order.getStatus() != Const.ORDER_STATUS.SENDED.getCode()){
            return ServerResponse.createByErrorMessage("订单未发货，不能确认收货");
        }
        order.setStatus(Const.ORDER_STATUS.SUCCESS.getCode());
        order.setEndTime(new Date());
        Integer rows = this.orderMapper.updateByPrimaryKeySelective(order);
        if (rows > 0){
            return ServerResponse.createBySuccessMessage("确认收货成功");
        }
        return ServerResponse.createByErrorMessage("确认收货失败");
    }

    //关闭2小时未付款的订单
    public void closeOrder(int hours){
        Date closeOrderBefore = DateUtils.addHours(new Date(),-hours); //创建时间小于该时间的订单全部被关闭
        List<Order> orderList = this.orderMapper.selectOrderByStatusAndCreateTime(Const.ORDER_STATUS.NO_PAY.getCode(),DateTimeUtil.date2String(closeOrderBefore));
        for (Order order : orderList){
            List<OrderItem> orderItemList = this.orderItemMapper.selectOrderItemsByOrderNo(order.getOrderNo());
            for (OrderItem orderItem : orderItemList){
                Integer stock = this.productMapper.selectStockByProductId(orderItem.getProductId());  //行锁
                if (stock == null){
                    continue;
                }
                Product updateProduct = new Product();
                updateProduct.setId(orderItem.getProductId());
                updateProduct.setStock(stock+orderItem.getQuantity());
                this.productMapper.updateByPrimaryKeySelective(updateProduct);
            }
            order.setCloseTime(new Date());
            order.setStatus(Const.ORDER_STATUS.CANCEL.getCode());
            this.orderMapper.updateByPrimaryKeySelective(order);
        }
    }
}
